package com.zhugang.week13.linkedlist;


/**
 * @program algorithms
 * @description: reverseKGroup
 * @author: chanzhugang
 * @create: 2022/10/27 22:36
 */
public class ReverseKGroup {

    /**
     * 25 K 个一组翻转链表
     * https://leetcode.cn/problems/reverse-nodes-in-k-group/
     * 可以多写写，锻炼编程能力，遇到问题要抱着高兴的态度，锻炼能力
     *
     * @param head
     * @param k
     * @return
     */
    public ListNode reverseGroup(ListNode head, int k) {
        // 画图理解： 锻炼编程能力，多写
        // newNode + tail， 每遍历k个翻转一次
        ListNode dummyHead = new ListNode();
        ListNode tail = dummyHead;

        ListNode p = head;
        while (p != null) {
            // 每k个重制为0
            int count = 0;
            ListNode q = p;
            while (q != null) {
                count++;
                if (count == k) {
                    break;
                }
                q = q.next;
            }

            if (q == null) {
                // 不够k个,不需要翻转
                tail.next = p;
                return dummyHead.next;
            } else {
                ListNode next = q.next;
                // 翻转p-q逻辑
                ListNode[] nodes = reverse(p, q);
                tail.next = nodes[0];
                // tail指向新的head
                tail = nodes[1];
                p = next;
            }
        }
        return dummyHead.next;
    }

    private ListNode[] reverse(ListNode head, ListNode tail) {
        // 翻转：头插法，定义结果链表
        ListNode newHead = null;
        ListNode p = head;

        while (p != tail) {
            ListNode next = p.next;
            // 头插法，翻转链表
            p.next = newHead;
            newHead = p;
            p = next;
        }
        tail.next = newHead;
        newHead = tail;

        return new ListNode[]{tail, head};
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}